const { getAll, update, remove, add, getCount } = require('../../utils/dbTools');
const tableName = 'position';
/**
 * 获取数据总条数
 * 
*/

const positionTotal = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const result = await getCount(tableName);
    if (!result) {
        output.code = 500;
        output.msg = '操作失败';
    }
    output.data = result;
    res.send(output);
}

/**
 * 获取职务列表
 * 
*/
const positionList = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { page, size } = req.query;
    if (!page || !size) {
        output.code = 500;
        output.msg = "参数错误";
        return res.send(output);
    }
    const map = { page, size };
    // 根据状态筛选


    const result = await getAll(tableName, map);
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    output.data = result;
    res.send(output);
}

/**
 * 新增职务信息
 * 
*/

const positionAdd = async (req, res) => {
    const output = {
        code: 200,
        msg: 'success'
    }
    // 获取登录账号id
    const { id: author_id, bus_id } = req.adminLoginInfo
    const { name, status } = req.body;
    if (!name || !status) {
        output.code = 500;
        output.msg = "参数错误";
        return res.send(output);
    }
    const data = { name, status, author_id, bus_id }
    const result = await add(data, tableName);
    if (!result) {
        output.code = 500;
        output.msg = '操作失败';
        return res.send(output);
    }
    res.send(output);
}

/**
 *  删除职务信息
 * 
*/

const positionRemove = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }

    const { id } = req.query;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误";
        return res.send(output);
    }

    const result = await remove(id, tableName);
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    res.send(output);
}

/**
 * 更新职务信息: 仅支持更新状态
*/
const positionUpdate = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    let { id, name, status } = req.body;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误";
        return res.send(output);
    }
    const result = await update(id, { name, status }, tableName);
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    res.send(output);
}


module.exports = {
    positionAdd,
    positionRemove,
    positionUpdate,
    positionList,
    positionTotal
}